﻿using System;
using System.Device.Location;
using System.Globalization;
using Newtonsoft.Json;

namespace CkSoftware.GroupMe.Sdk.Core.Dao
{
	/// <summary>
	/// GroupMe message location attachment.
	/// </summary>
	public class GroupMeLocationAttachment : GroupMeAttachmentBase
	{
		/// <summary>
		/// The latitude of the location.
		/// </summary>
		[JsonProperty("lat")]
		public string Latitude { get; set; }

		/// <summary>
		/// The longitude of the location.
		/// </summary>
		[JsonProperty("lon")]
		public string Longitude { get; set; }

		/// <summary>
		/// The name which should be displayed at this location.
		/// </summary>
		[JsonProperty("name")]
		public string Name { get; set; }

		/// <summary>
		/// Defines the type of the attachment implementation.
		/// </summary>
		public override AttachmentType Type
		{
			get { return AttachmentType.Location; }
		}

		/// <summary>
		/// Parses the current coordinates into a <see cref="GeoCoordinate" /> object.
		/// </summary>
		/// <exception cref="InvalidOperationException">Occurs if the Latitude or Longitude properties are empty.</exception>
		/// <exception cref="FormatException">
		/// Occurs if the given latitude or longitude cannot be parsed into a
		/// <see cref="GeoCoordinate" /> object.
		/// </exception>
		/// <returns>The <see cref="GeoCoordinate" /> object instance representing this location.</returns>
		public GeoCoordinate AsCoordinates()
		{
			if (string.IsNullOrEmpty(Latitude) || string.IsNullOrEmpty(Longitude))
			{
				throw new InvalidOperationException(
					"The coordinates can only be constructed if there are values in both Latitude and Longitude properties.");
			}

			double lat;
			double lon;

			if (double.TryParse(Latitude, out lat) && double.TryParse(Longitude, out lon))
			{
				return new GeoCoordinate(lat, lon);
			}

			throw new FormatException(string.Format(CultureInfo.CurrentCulture,
				"Either Latitude or Longitude parameter are in a wrong format (lat: '{0}', lon: '{1}').",
				Latitude,
				Longitude));
		}
	}
}